package la.iok.hzsvn.lewin.movie.operation.controller;

import com.alipay.easysdk.factory.Factory;
import la.iok.hzsvn.lewin.movie.operation.entity.ChargeOrder;
import la.iok.hzsvn.lewin.movie.operation.service.ChargeOrderService;
import la.iok.hzsvn.lewin.movie.operation.service.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("aliPay")
public class AliPayNotifyController {
    private static final Logger logger = LoggerFactory.getLogger(AliPayNotifyController.class);
    private final PayService payService;
    private final ChargeOrderService chargeOrderService;

    public AliPayNotifyController(@Qualifier("aliPayService") PayService payService, ChargeOrderService chargeOrderService) {
        this.payService = payService;
        this.chargeOrderService = chargeOrderService;
    }

    @RequestMapping("notify")
    public void notifyCallBack(HttpServletRequest request){
        Map< String , String > params = new HashMap< String , String >();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        try {
            if(Factory.Payment.Common().verifyNotify(params)){
                ChargeOrder order = new ChargeOrder();
                order.setUuid(params.get("out_trade_no"));
                payService.queryOrder(order);
                chargeOrderService.update(order);
            }else{
                logger.error("支付宝通道验证签名失败:{}",params);
            }
        } catch (Exception e) {
            logger.error("支付宝通道验证签名失败",e);
        }
    }
}
